package com.bridgeintelligent.tag.user.mgmt.service;

import com.alibaba.fastjson.JSON;
import com.bridgeintelligent.tag.user.mgmt.entity.UserCodes;
import com.bridgeintelligent.tag.user.mgmt.mapper.RoleMgmtMapper;
import com.bridgeintelligent.tag.user.mgmt.pojo.Role;
import com.bridgeintelligent.tag.user.mgmt.pojo.RoleModel;
import com.bridgeintelligent.tag.user.mgmt.pojo.RolePO;
import com.bridgeintelligent.tag.user.mgmt.pojo.TagPermission;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 用户服务层接口实现
 */
@Slf4j
@Service
@Transactional
public class RoleMgmtServiceImpl implements RoleMgmtService {

    @Autowired
    private RoleMgmtMapper roleMgmtMapper;
    @Autowired
    private TagPermMgmtService tagPermMgmtService;

    /**
     * 子系统名称简称
     */
    private static final String SYSTEM_NAME = "CBMRS";
    /**
     * 默认总行分行可见
     */
    private static final String INIT_VISILIBITY = "3";
    /**
     * 默认普通角色
     */
    private static final String INIT_IMPORTANCE = "1";

    /**
     * 新增角色
     *
     * @param
     * @return
     */
    @Transactional
    @Override
    public void addRole(String roleName, String roleDsc, String[] powerIds, List<TagPermission> tagPerms) {
        Role role = new Role();
        //设置id
        String roleId = IDGenerator.gen();
        role.setRoleId(roleId);
        //默认有效
        role.setEfftctiveSymbol(UserCodes.EFFTCTIVE_SYMBOL_01);
        role.setRoleName(roleName);
        role.setRoleDsc(roleDsc);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        role.setOperateTime(sdf.format(new Date()));
        roleMgmtMapper.addRole(role);
        //设置角色与权限的关联关系
        if (powerIds != null) {
            setRoleAndPower(roleId, powerIds);
        }
        tagPermMgmtService.delete(roleId);
        if ( (tagPerms != null) && ( !tagPerms.isEmpty() ) ) {
            for ( TagPermission tagPerm : tagPerms ) {
                tagPerm.setRoleId(roleId);
                tagPermMgmtService.add( tagPerm );
            }
        }

       //推送角色信息
        // if (!synchRoleInfo(roleId, roleName, "01", roleDsc)){
        //     throw new RoleException(new ExceptionCode(40003, "同步角色信息失败"));
        // }

    }

    /**
     * 删除角色
     *
     * @param roleId
     */
    @Transactional
    @Override
    public void deleteRoleByRoleId(String roleId) {

        //删除角色与权限的关联关系
        roleMgmtMapper.deleteRoleAndPower(roleId);
        //删除角色
        roleMgmtMapper.deleteRoleByRoleId(roleId);
        tagPermMgmtService.delete(roleId);

        //推送角色信息
        // if (!synchRoleInfo(roleId, roleName, "03", "此角色已删除")){
        //     throw new RoleException(new ExceptionCode(40003, "同步角色信息失败"));
        // }
    }


    /**
     * 修改角色信息
     *
     * @param roleId
     * @param roleName
     * @param roleDsc
     * @param pwoerIds
     */
    @Transactional
    @Override
    public void updateRole(String roleId, String roleName, String roleDsc, String[] pwoerIds, List<TagPermission> tagPerms) {
        if (pwoerIds != null) {
            //删除角色与权限的关联关系
            roleMgmtMapper.deleteRoleAndPower(roleId);
            //设置角色与权限的关联关系
            setRoleAndPower(roleId, pwoerIds);
        }
        //修改角色
        Role role = new Role();
        role.setRoleId(roleId);
        role.setRoleName(roleName);
        role.setRoleDsc(roleDsc);
        //修改信息后默认为有效
        role.setEfftctiveSymbol(UserCodes.EFFTCTIVE_SYMBOL_01);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        role.setOperateTime(sdf.format(new Date()));
        roleMgmtMapper.updateRole(role);
        tagPermMgmtService.delete(roleId);
        if ( (tagPerms != null) && ( !tagPerms.isEmpty() ) ) {
            for ( TagPermission tagPerm : tagPerms ) {
                tagPerm.setRoleId(roleId);
                tagPermMgmtService.add( tagPerm );
            }
        }

        //推送角色信息
        // if (!synchRoleInfo(roleId, roleName, "02", roleDsc)){
        //     throw new RoleException(new ExceptionCode(40003, "同步角色信息失败"));
        // }
    }
    @Override
    public boolean synchRoleInfo(String roleId, String roleName, String roleType, String remark) {
        //组装信息
        RoleModel model = new RoleModel();
        model.setSystemShortName(SYSTEM_NAME);
        List<RolePO> roleList = new ArrayList<>(1);
        RolePO role = new RolePO();
        role.setRoleId(roleId);
        role.setRoleName(roleName);
        role.setRoleType(roleType);
        role.setRemark(remark);
        role.setVisibility(INIT_VISILIBITY);
        role.setImportance(INIT_IMPORTANCE);
        roleList.add(role);
        model.setRoleList(roleList);
        String roleStr = JSON.toJSONString(model);
        log.info("{}：---组装角色信息：{}",roleName,roleStr);
        /* NOTE 强绑定(光大信用卡)
         * 推送role信息
        String reqIp = roleMgmtMapper.ccisUrl();
        log.info("获取ccis请求地址：{}",reqIp);
        String response = HttpClientUtil.doPostJson(reqIp, roleStr);
        log.info("{}:---返回角色同步响应：{}",roleName,response);
        if (!StringUtils.isEmpty(response)) {
            CcisModel ccisModel = JSONObject.parseObject(response, CcisModel.class);
            if (ccisModel != null && ccisModel.getResp_code() == 0){
                flag = true;
            }
        }
        return flag;
        */
        return true;
    }


    /**
     * 设置角色和权限的关联关系
     *
     * @param roleId
     * @param powerIds
     */
    @Override
    public void setRoleAndPower(String roleId, String[] powerIds) {
        if (powerIds == null || powerIds.length < 1) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        for (String powerId : powerIds) {
            map.put("ROLE_ID", roleId);
            map.put("POWER_ID", powerId);
            String id = IDGenerator.gen();
            map.put("id", id);
            roleMgmtMapper.setRoleAndPower(map);
        }
    }

}
